//
//  HACStockDetailComponent.m
//  Pods
//
//  Created by Hotacool on 2017/9/5.
//
//

#import "HACStockDetailComponent.h"

static const CGFloat refreshOffsetX = 30;
#define defaultBkColor [UIColor colorWithWhite:0.9 alpha:0.5]
@interface HACStockDetailComponent () <UIGestureRecognizerDelegate, UIScrollViewDelegate>
@property (nonatomic, strong, readwrite) UIScrollView *contentView;

@property (nonatomic, strong, readwrite) UILabel *xCursorLabel; // y轴的文字提示
@property (nonatomic, strong, readwrite) UILabel *yCursorLabel; // x轴的文字提示
@property (nonatomic, strong, readwrite) CAShapeLayer *focusLayer;

//@property (nonatomic, assign, readwrite) BOOL isRefresh;
@property (nonatomic, strong, readwrite) UIActivityIndicatorView *refreshIndicator;
@end

@implementation HACStockDetailComponent

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setUp];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setUp];
    }
    return self;
}

- (void)setUp {
    self.focusEnable = YES;
    self.indexFromEnd = 0;
    self.focusItemsCount = 2;
    
    _focusComponent = [HACFocusComponents new];
    // 点击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [self addGestureRecognizer:tapGesture];
    
    // 添加长按手势
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesture:)];
    longPressGesture.delegate = self;
    longPressGesture.minimumPressDuration = 0.5;
    [self addGestureRecognizer:longPressGesture];
    
    // 添加缩放手势
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGesture:)];
    [self addGestureRecognizer:pinchGesture];
    
    // add contentView
    self.contentView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    [self addSubview:self.contentView];
    
    // 添加focus
    self.focusLayer = [[CAShapeLayer alloc] init];
    self.focusLayer.frame = self.bounds;
    self.focusLayer.backgroundColor = [[UIColor clearColor] CGColor];
    self.focusLayer.contentsScale = [[UIScreen mainScreen] scale];
    self.focusLayer.strokeColor = [UIColor blackColor].CGColor;
    [self.layer addSublayer:self.focusLayer];
    //focus文字
    self.xCursorLabel = [[UILabel alloc] init];
    self.xCursorLabel.backgroundColor = defaultBkColor;
//    self.xCursorLabel.layer.borderColor = [UIColor brownColor].CGColor;
//    self.xCursorLabel.layer.borderWidth = 1;
    [self addSubview:self.xCursorLabel];
    
    self.yCursorLabel = [[UILabel alloc] init];
    self.yCursorLabel.backgroundColor = defaultBkColor;
//    self.yCursorLabel.layer.borderColor = [UIColor brownColor].CGColor;
//    self.yCursorLabel.layer.borderWidth = 1;
    [self addSubview:self.yCursorLabel];

    _refreshIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [self.contentView addSubview:_refreshIndicator];
}

- (void)setFrame:(CGRect)frame {
    [super setFrame:frame];
    self.contentView.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
    self.refreshIndicator.center = CGPointMake(-refreshOffsetX+12, frame.size.height/2);
}

- (void)refreshWithData:(HACChartData *)data {
    _data = data;
}

- (void)refreshWithIncrementData:(HACChartData *)data {
    _data = [_data appendWithData:data];
}

- (void)endRefreshWithData:(HACChartData *)data {
    _data = data;
    [self.refreshIndicator stopAnimating];
    CGPoint offset = self.contentView.contentOffset;
    [self.contentView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.contentView setContentOffset:offset animated:NO];
    _isRefresh = NO;
}

- (void)resetToLatest {
    
}

- (void)reset {
    _data = nil;
    _isRefresh = NO;
}

- (UIScrollView *)contentView {
    if (!_contentView) {
        _contentView = [[UIScrollView alloc] initWithFrame:CGRectZero];
        _contentView.backgroundColor = [UIColor clearColor];
        _contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _contentView.showsHorizontalScrollIndicator = NO;
        _contentView.showsVerticalScrollIndicator = NO;
        _contentView.alwaysBounceHorizontal = YES; // 保证可以滑动和最后回到offset为0
        _contentView.delegate = self;
        _contentView.bounces = NO;
    }
    return _contentView;
}

#pragma mark - gestures
#pragma mark ----- UIGestureRecognizer
- (void)tapGesture:(UITapGestureRecognizer *)gesture {
    [self reactForTapGesture:gesture];
    [self drawingFocusLayer];
    if ([self.delegate respondsToSelector:@selector(tapedStockComponent:gesture:)]) {
        [self.delegate tapedStockComponent:self gesture:gesture];
    }
}

- (void)longPressGesture:(UILongPressGestureRecognizer *)gesture {
    if (!self.focusEnable) {
        return;
    }
    [self reactForLongPressGesture:gesture];
    [self drawingFocusLayer];
    if ([self.delegate respondsToSelector:@selector(dragStockComponent:gesture:)]) {
        [self.delegate dragStockComponent:self gesture:gesture];
    }
}

- (void)pinchGesture:(UIPinchGestureRecognizer *)gesture {
    [self reactForPinchGesture:gesture];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES;
}

#pragma mark -- scroll delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self reactForContentViewDidScroll:scrollView];
    if (scrollView.contentOffset.x < 0 && !self.isRefresh) {
        [self.refreshIndicator startAnimating];
        if (scrollView.contentOffset.x <= -refreshOffsetX) {
            self.isRefresh = YES;
            [self.contentView setContentInset:UIEdgeInsetsMake(0, refreshOffsetX, 0, 0)];
            if ([self.delegate respondsToSelector:@selector(stockDetailNeedRefresh:)]) {
                [self.delegate stockDetailNeedRefresh:self];
            }
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
}
#pragma mark -- action for override
- (void)reactForTapGesture:(UITapGestureRecognizer *)gesture {
    self.focusPoint = CGPointZero;
    self.focusIndex = -1;
}

- (void)reactForLongPressGesture:(UILongPressGestureRecognizer*)gesture {
    CGPoint point = [gesture locationInView:self];
    if (gesture.state == UIGestureRecognizerStateBegan || gesture.state == UIGestureRecognizerStateChanged) {
        self.focusPoint = point;
        self.focusIndex = 1;
    } else {
        self.focusPoint = CGPointZero;
        self.focusIndex = -1;
    }
}

- (void)reactForPinchGesture:(UIPinchGestureRecognizer *)gesture {
    
}

- (void)reactForContentViewDidScroll:(UIScrollView *)scrollView {
    
}

#pragma mark - provider
- (NSArray *)focusDataInRect:(CGRect)rect focusIndex:(NSInteger)focusIndex {
    if (self.focusItemsCount == 0 || focusIndex == -1)
        return nil;
    NSMutableArray *focusDrawingData = [NSMutableArray array];
    CGFloat x = 0.0, y = 0.0;
    for (NSInteger i = 0; i < self.focusItemsCount; i++) {
        HACFocusComponents *item = [[HACFocusComponents alloc] init];
        item.index = i;
        item.axisType = i == 0 ? DrawingAxisTypeY : DrawingAxisTypeX; //第一根是竖线，第二根横线
        item.text = [self stringForFocusItem:item focusIndex:focusIndex];
        
        CGSize textSize = [item.text sizeWithAttributes:@{NSFontAttributeName : item.textFont}];
        CGRect frame = CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect), textSize.width , textSize.height);
        CGLine line = CGLineMake(0, 0, 0, 0);
        
        CGPoint focusPoint = self.focusPoint;
        
        if (item.axisType == DrawingAxisTypeX) {
            y = focusPoint.y;
            line = CGLineMake(CGRectGetMinX(rect) + textSize.width, y, CGRectGetMaxX(rect), y);
            frame.origin.y = MIN(CGRectGetMaxY(rect), MAX(CGRectGetMinY(rect), y - textSize.height / 2));
        } else {
            x = focusPoint.x;
            line = CGLineMake(x, CGRectGetMinY(rect), x, CGRectGetMaxY(rect));
            frame.origin.x = MIN(CGRectGetMaxX(rect) - textSize.width, MAX(CGRectGetMinX(rect), x - textSize.width / 2));
            frame.origin.y = CGRectGetMaxY(rect);
        }
        
        item.textFrame = frame;
        item.line = line;
        item.point = focusPoint;
        item.lineColor = self.focusComponent.lineColor?:item.lineColor;
        item.lineBolder = self.focusComponent.lineBolder?:item.lineBolder;
        item.borderWidth = self.focusComponent.borderWidth?:item.borderWidth;
        item.bgColor = self.focusComponent.bgColor?:item.bgColor;
        item.borderColor = self.focusComponent.bgColor?:item.bgColor;
        item.textFont = self.focusComponent.textFont?:item.textFont;
        item.textAlignment = self.focusComponent.textAlignment?:item.textAlignment;
        [focusDrawingData addObject:item];
    }
    return focusDrawingData;
}

- (NSString *)stringForFocusItem:(HACFocusComponents *)focusItem focusIndex:(NSInteger)focusIndex {
    NSString *focusString;
    if (focusItem.axisType == DrawingAxisTypeX) {
        focusString = @"X";
    } else {
        focusString = @"Y";
    }
    return focusString;
}

#pragma  markt - drawing
- (void)drawingFocusLayer {
    if (self.focusIndex == -1) {
        // 清除
        self.focusLayer.path = NULL;
        self.xCursorLabel.hidden = YES;
        self.yCursorLabel.hidden = YES;
    } else {
        self.xCursorLabel.hidden = NO;
        self.yCursorLabel.hidden = NO;
        
        @autoreleasepool {
            CGMutablePathRef path = CGPathCreateMutable();
            //            CGRect offsetCenterFrame = [self offsetRectForOriginalRect:self.timeLineView.frame];
            CGRect offsetCenterFrame = self.bounds;
            NSArray *datas = [self focusDataInRect:offsetCenterFrame focusIndex:self.focusIndex];
            
            for (HACFocusComponents *obj in datas) {
                UILabel *label = obj.axisType == DrawingAxisTypeX ? self.xCursorLabel : self.yCursorLabel;
                label.text = obj.text;
                label.frame = obj.textFrame;
                label.font = obj.textFont;
                label.textColor = obj.textColor;
                label.backgroundColor = obj.fillColor?:defaultBkColor;
                label.textAlignment = obj.textAlignment?:NSTextAlignmentLeft;
                
                CGLine line = obj.line;
                if (obj.axisType == DrawingAxisTypeY) {
                    // y轴需要从最上面到最下面
                    line.start.y = 0;
                    line.end.y = CGRectGetMaxY(self.bounds);
                }
                
                if (obj.axisType == DrawingAxisTypeY) {
                    CGPathAddArc(path, NULL, obj.point.x, obj.point.y, 2, 0, 2 * M_PI, NO);
                }
                CGPathMoveToPoint(path, NULL, line.start.x, line.start.y);
                CGPathAddLineToPoint(path, NULL, line.end.x, line.end.y);
                CGPathCloseSubpath(path);
            }
            self.focusLayer.strokeColor = self.focusComponent.lineColor.CGColor;
            self.focusLayer.borderWidth = self.focusComponent.borderWidth;
            self.focusLayer.lineWidth = self.focusComponent.borderWidth;
            self.focusLayer.path = path;
            CFRelease(path);
        }
    }
}

@end
